package apiController

import (
	"encoding/json"
	"gin/chibuda/app/utils"
	"gin/chibuda/system/ws"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	uuid "github.com/satori/go.uuid"
	"net/http"
	"time"
)

func Index(c *gin.Context)  {
	conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		http.NotFound(c.Writer, c.Request)
		return
	}
	client := &ws.Client{
		Id:     uuid.NewV4().String(),
		Group:  "test",
		Socket: conn,
		Message:   make(chan []byte, 1024),
		ReadMessage:   make(chan []byte, 1024),
		State:true ,
	}
	go ws.WebsocketManager.Start()
	ws.WebsocketManager.RegisterClient(client)
	go client.Read()
	go client.Write()
	go ws.WebsocketManager.SendService()
	go ws.WebsocketManager.SendGroupService()
	go ws.WebsocketManager.SendAllService()
	go heartbeat(client)  //心跳 检测
	for {
		if !client.State {
			return
		}
		select {
			case msg ,_ := <- client.ReadMessage:
				postParm:=make(map[string]string)
				json.Unmarshal([]byte(string(msg)), &postParm)
				rsMessage := webSocketRoute(client,postParm)
				ws.WebsocketManager.Send(client.Id,client.Group,[]byte(rsMessage))
		}
	}
}

func heartbeat(client *ws.Client){
	for  {
		ws.WebsocketManager.Send(client.Id,client.Group,[]byte("心跳"))
		time.Sleep(time.Duration(1)*time.Second)
	}
}

func webSocketRoute(client *ws.Client, data map[string]string) string{
	rsMessage:=make( map[string]interface{})
	if data["do"] == "bindUser" {
		groupLen := len(ws.WebsocketManager.Group[client.Group])
		rsMessage["do"] = "bindUser"
		rsMessage["groupLens"] = groupLen
	}
	return  utils.Json_encode(rsMessage)
}